﻿using SanJ.FreeCare.ValueSets;
using SanJ.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Services;
using Volo.Abp.OpenIddict;

namespace SanJ.FreeCare.ObservationDefinitions
{
    public class ObservationDefinitionManager : DomainService
    {
        private readonly IObservationDefinitionRepository _observationDefinitionRepository;

        public ObservationDefinitionManager(IObservationDefinitionRepository observationDefinitionRepository)
        {
            _observationDefinitionRepository = observationDefinitionRepository;
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="observationDefinition">ObservationDefinition 实体</param>
        /// <returns></returns>
        public async Task<ObservationDefinition> CreateAsync(ObservationDefinition observationDefinition)
        {
            //自动生成code
            observationDefinition.Code = await GetNextChildCodeAsync(observationDefinition.ParentId);
            //如果父节点id为空，则自动new
            if (observationDefinition.ParentId == Guid.Empty)
            {
                observationDefinition.ParentId = Guid.NewGuid();
            }
            if (observationDefinition.IsVaild.IsNullOrEmpty())
            {
                observationDefinition.IsVaild = VaildType.Vaild;
            }
            return await _observationDefinitionRepository.InsertAsync(observationDefinition);
        }

        /// <summary>
        /// 批量创建
        /// </summary>
        /// <param name="observationDefinition">ObservationDefinition 实体</param>
        /// <returns></returns>
        public async Task CreateManyAsync(List<ObservationDefinition> observationDefinitions)
        {
            foreach (var observationDefinition in observationDefinitions)
            {
                //自动生成code
                observationDefinition.Code = await GetNextChildCodeAsync(observationDefinition.ParentId);
                //如果父节点id为空，则自动new
                if (observationDefinition.ParentId == Guid.Empty)
                {
                    observationDefinition.ParentId = Guid.NewGuid();
                }
                if (observationDefinition.IsVaild == string.Empty)
                {
                    observationDefinition.IsVaild = VaildType.Vaild;
                }
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="observationDefinition">ObservationDefinition 实体</param>
        /// <returns></returns>
        public async Task<ObservationDefinition> UpdateAsync(Guid id, ObservationDefinition observationDefinition)
        {
            return await _observationDefinitionRepository.UpdateAsync(observationDefinition);
        }

        /// <summary>
        /// 批量修改
        /// </summary>
        /// <param name="observationDefinition">ObservationDefinition 实体</param>
        /// <returns></returns>
        public Task UpdateBatchAsync(List<ObservationDefinition> observationDefinitions)
        {
            return _observationDefinitionRepository.UpdateManyAsync(observationDefinitions);
        }

        /// <summary>
        /// 获取所有数据
        /// </summary>
        /// <param name="observationDefinition">ObservationDefinition 实体</param>
        /// <returns></returns>
        public async Task<List<ObservationDefinition>> GetListAsync()
        {
            return await _observationDefinitionRepository.GetListAsync();
        }

        /// <summary>
        /// 获取所有有效数据
        /// </summary>
        /// <param name="observationDefinition">ObservationDefinition 实体</param>
        /// <returns></returns>
        public async Task<List<ObservationDefinition>> GetVaildListAsync()
        {
            return await _observationDefinitionRepository.GetListAsync(p => p.IsVaild == VaildType.Vaild);
        }

        /// <summary>
        /// 分页查询有效数据
        /// </summary>
        /// <param name="pageCount">每页数量</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="filter">name 过滤</param>
        /// <returns></returns>
        public async Task<List<ObservationDefinition>> GetPageLisAsync(string filter,string sorting, int maxResultCount = int.MaxValue,
            int skipCount = 0)
        {
            return await _observationDefinitionRepository.GetPageLisAsync(filter, sorting, maxResultCount, skipCount);
        }

        /// <summary>
        /// 分页查询有效数据的总数量
        /// </summary>
        /// <param name="filter">name 过滤</param>
        /// <returns></returns>
        public async Task<long> GetCountAsync(string filter)
        {
            return await _observationDefinitionRepository.GetCountAsync(filter);
        }

        /// <summary>
        /// 通过Patientid 获取所有子节点
        /// </summary>
        /// <param name="patientId">父节点id</param>
        /// <returns></returns>
        public async Task<List<ObservationDefinition>> GetListByPatientIdAsync(Guid? patientId)
        {
            return await _observationDefinitionRepository.GetListAsync(p => p.ParentId == patientId);
        }

        /// <summary>
        /// 根据id获取数据内容
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public async Task<ObservationDefinition> GetByIdAsync(Guid? id)
        {
            return (await _observationDefinitionRepository.GetListAsync(p => p.Id == id)).FirstOrDefault();
        }

        public Task Delete(Guid id)
        {
            return _observationDefinitionRepository.DeleteAsync(id);
        }

        private async Task<string> GetNextChildCodeAsync(Guid? patientId)
        {
            var lastChild = await GetLastChildOrNullAsync(patientId);
            if (lastChild != null)
            {
                return HierarchicalCodeManager.CalculateNextCode(lastChild.Code);
            }

            string? parentCode = null;
            if (patientId == null || patientId != Guid.Empty)
            {
                parentCode = null;
            }
            else
            {
                parentCode = (await GetByIdAsync(patientId)).Code;
            }
            return HierarchicalCodeManager.AppendCode(parentCode, HierarchicalCodeManager.CreateCode(1));
        }

        /// <summary>
        /// 同一级别机构，根据code排序，获取最后一个
        /// </summary>
        /// <param name="patientId"></param>
        /// <returns></returns>
        private async Task<ObservationDefinition> GetLastChildOrNullAsync(Guid? patientId)
        {
            var children = await this.GetListByPatientIdAsync(patientId);
            return children.OrderBy(c => c.Code).LastOrDefault();
        }

        public async Task<IEnumerable<object>> GetPageLisAsync(string filterText, object sorting, object maxResultCount, object skipCount)
        {
            throw new NotImplementedException();
        }
    }
}
